<template>
  <tr v-for="(item, index) of tBody" :key="item.id">
    <td v-for="(value, key) in item" :key="key" 
    @click.stop="onClick($event, key, index)"
    >
      {{ value }}
    </td>
  </tr>
</template>

<script setup>
import EditInput from './common/EditInput.vue';
const { createApp } = require('@vue/runtime-dom');

const props = defineProps({
  tBody: {
    type: Array,
    default: () => [],
  },
  tHead: {
    type: Array,
    default: () => [],
  },
});

const emits = defineEmits(['changeValue'])

let { tHead, tBody } = props,
  k, idx,
  editInput; // input 输入框实例

// 1.点击事件
const onClick = function (event, key, index) {
  k = key, idx = index;
  onEditIptMounted();

  const tar = event.target,
    //  是否可编辑
    isEdit = tHead.find((item) => item.key === key).isEdit;

  // 2. 判断是否可编辑
  if (isEdit) {
    const oFrag = document.createDocumentFragment();
    // 2.1 创建组件 实例
    editInput = createApp(EditInput, {
      textCont: tar.value,
      setValue,
    });

    // 2.2 组件实例 真实节点挂载到 ofrag中
    editInput.mount(oFrag);

    // 2.3 将 ofrag 碎片放入td中
    tar.appendChild(oFrag);
  }
};

document.addEventListener(
  'click',
  function () {
    onEditIptMounted();
  },
  false
);

// 3. 设置 input 输入框的值
function setValue(value) {
  value ? emits('changeValue', {
    k,
    idx,
    value,
  }, onEditIptMounted) : '';
}

// 卸载 input 组件功能函数
function onEditIptMounted() {
  editInput && editInput.unmount();
}
</script>

<style lang="scss" scoped>
td {
  position: relative;
}
</style>
